<template>
  <div>
    <div class="sku_select">
      <!-- 添加规格-->
      <el-row v-if="fg">
        <el-col :span="2">添加规格:</el-col>
        <el-col :span="8">
          <el-input
            v-model="Specs"
            placeholder="请输入内容"
            size="small"
            @keyup.enter.native="addSpecs"
          >
            <el-button slot="append" @click="addSpecs">添加规格</el-button>
          </el-input>
        </el-col>
      </el-row>
      <!-- 添加参数-->
      <el-row class="specs_box" v-if="fg">
        <div
          class="specs_item"
          ref="check"
          v-for="(item, i) of SpecsList"
          :key="i"
        >
          <div class="specs_titt">{{ item.key }}</div>
          <div class="specs_key">
            <el-checkbox-group
              v-model="item.checkedAttr"
              @change="checkboxChange(item)"
            >
              <el-checkbox
                v-for="(value, j) in item.value"
                :label="value"
                :key="j"
                >{{ value.value }}</el-checkbox
              >
            </el-checkbox-group>
          </div>
          <div class="specs_add">
            <el-input
              v-model="attribute[i].values"
              placeholder="请输入内容"
              size="small"
              @keyup.enter.native="
                addAttribute(attribute[i].values, item.id, item.value)
              "
            >
              <el-button
                slot="append"
                @click="addAttribute(attribute[i].values, item.id, item.value)"
                >添加参数</el-button
              >
            </el-input>
          </div>
        </div>
      </el-row>
    </div>
    <div class="table_box">
      <el-table ref="SkuData" :data="SkuData" style="width: 100%" border>
        <template v-for="(item, index) in checkedAttr" v-show="fg">
          <el-table-column
            :label="item.key"
            :key="item.value.specId"
            align="center"
          >
            <template slot-scope="scope">
              {{ item.value.value }}
              <p v-if="false">{{ index }}{{ scope }}</p>
            </template>
          </el-table-column>
        </template>
        <!-- 名称 -->
        <el-table-column label="名称" align="center">
          <template slot-scope="scope">
            <el-input v-model="scope.row.goodsName"></el-input>
          </template>
        </el-table-column>
        <!-- 价格 -->
        <el-table-column label="价格" align="center">
          <template slot-scope="scope">
            <el-input v-model="scope.row.goodsPrice"></el-input>
          </template>
        </el-table-column>
        <!-- 商品图片 -->
        <el-table-column label="商品图片" align="center">
          <template slot-scope="scope">
            <img
              :src="scope.row.goodsImage"
              alt="image"
              class="head"
              style="width: 100px; height: 100px"
            />
            <form name="form1" id="form1">
              <input
                type="file"
                ref="inp"
                name="file"
                id="file"
                @change="fn"
                accept="image/jpg,image/jpeg,image/png,image/PNG"
              />
            </form>
            <label for="file" class=" ">选择图片</label>
          </template>
        </el-table-column>
        <!-- 分类 -->
        <el-table-column label="分类" align="center">
          <template slot-scope="scope">
            <el-input v-model="scope.row.commodityTypeId"></el-input>
          </template>
        </el-table-column>
        <!-- 是否推荐(0为不推荐，1为推荐) -->
        <el-table-column label="是否推荐(0为不推荐，1为推荐)" align="center">
          <template slot-scope="scope">
            <el-input v-model="scope.row.recommend"></el-input>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="btn">
      <el-button @click="clicks(1)" v-if="Flog && fg">添加商品</el-button>
      <el-button @click="clickss(2)" v-else-if="!fg">修改商品</el-button>
      <el-button @click="clicks(0)" v-else-if="!Flog">添加商品规格</el-button>
      <el-button @click="back">返回</el-button>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      imgUrl: "",
      SkuData: [
        {
          skus: "",
          pskuId: "",
          goodsName: "",
          goodsPrice: "",
          goodsImage: "",
          commodityTypeId: "",
          recommend: "",
        },
      ], //skudata
      Specs: "", //添加的规格值
      attribute: [], //添加的参数值
      checkedAttr: [], //勾选详情
      SpecsList: [], //规格详情
      spanArr: [],
      operationData: [{ price: "", stock: "" }],
      Flog: true,
      fg: true,
    };
  },
  created() {},
  computed: {
    table() {
      var data = this.SkuData;
      return data;
    },
  },
  methods: {
    back() {
      this.$router.push("/backstage");
    },
    fn(e) {
      let _this = this; //在onload中this会丢失指针 提前保存this
      let imgSrc = window.URL.createObjectURL(e.target.files[0]);
      let files = e.target.files[0];
      let img = new Image();

      img.src = imgSrc;
      if (!e || !window.FileReader) return; // 看支持不支持FileReader
      let reader = new FileReader();
      _this.SkuData[0].goodsImage = "../../static/head/" + `${files.name}`;
      // reader.readAsDataURL(files); // 这里是最关键的一步，转换成base64
      // reader.onloadend = function () {
      //   _this.imgUrl = this.result; //返显图片
      // };
    },
    //添加规格
    addSpecs() {
      var that = this;
      var val = that.Specs;
      var list = that.SpecsList;
      var flog = true;
      if (val) {
        if (list.length > 0) {
          for (var i = 0; i < list.length; i++) {
            if (list[i].key == val) {
              alert("名称重复");
              that.Specs = "";
              flog = false;
              return;
            }
          }
          if (flog) {
            this.$axios
              .post("/goods/addSpec", {
                specName: this.Specs,
              })
              .then((res) => {
              });
          }
          that.Specs = "";
        }
      } else {
        alert("不能为空");
      }
      location.reload();
    },
    //添加参数
    addAttribute(value, id, list) {
      if (value) {
        if (list.indexOf(value) != -1) {
          return alert("已存在");
        } else {
          this.$axios
            .post("/goods/addSpecParam", {
              pspecId: id,
              specName: value,
            })
            .then((res) => {
            });
          location.reload();
        }
      } else {
        alert("不能为空");
      }
      value = "";
    },
    //勾选参数
    checkboxChange() {
      var that = this;
      var SpecsList = that.SpecsList;
      var arr = [];
      for (var i = 0; i < SpecsList.length; i++) {
        if (SpecsList[i].checkedAttr.length > 1) {
          SpecsList[i].checkedAttr.splice(0, 1);
        }
        if (SpecsList[i].checkedAttr.length > 0) {
          var obj = {};
          obj.id = SpecsList[i].id;
          obj.key = SpecsList[i].key;
          obj.value = SpecsList[i].checkedAttr[0];
          arr.push(obj);
        }
      }
      this.checkedAttr = arr;

      var arrt = this.checkedAttr;
      var pskuid = "";
      var skus = "";
      for (let i = 0; i < arrt.length; i++) {
        pskuid += arrt[i].id + ",";
        skus += `${arrt[i].value.pspecId};${arrt[i].value.specId},`;
      }
      pskuid = pskuid.substr(0, pskuid.length - 1);
      skus = skus.substr(0, skus.length - 1);
      this.SkuData[0].skus = skus;
      this.SkuData[0].pskuId = pskuid;
    },
    // 发送添加商品请求
    clicks(vals) {
      var obj = this.SkuData[0];
      var flog = true;
      for (const key in obj) {
        if (obj[key] == "") {
          flog = false;
          break;
        }
      }
      if (flog) {
        if (vals == 1) {
          this.$axios
            .post("goods/addGoods", {
              skus: obj.skus,
              pskuId: obj.pskuId,
              goodsName: obj.goodsName,
              goodsPrice: obj.goodsPrice,
              goodsImage: obj.goodsImage,
              status: "1",
              commodityTypeId: obj.commodityTypeId,
              recommend: obj.recommend,
            })
            .then((res) => {
              if (res.data.data) {
                alert("添加商品成功！");
                this.$router.push("/backstage");
              }
            });
        } else if (vals == 0) {
          this.$axios
            .post("goods/addGoodsSku", {
              skus: obj.skus,
              pskuId: obj.pskuId,
              goodsName: obj.goodsName,
              goodsPrice: obj.goodsPrice,
              goodsImage: obj.goodsImage,
              status: "1",
              commodityTypeId: obj.commodityTypeId,
              recommend: obj.recommend,
              goodsId: this.$route.query.id,
            })
            .then((res) => {
              if (res.data.data) {
                alert("添加商品规格！");
                this.$router.push("/backstage");
              }
            });
        }
      } else {
        alert("请将信息填写完整");
      }
    },
    clickss(vals) {
      var obj = this.SkuData[0];
      obj.skus = "0";
      obj.pskuId = "0";
      var ffg = true;
      for (const key in obj) {
        if (obj[key] == "") {
          ffg = false;
          break;
        }
      }
      if (ffg) {
        this.$axios
          .post("goods/updateGoodsById", {
            goodsName: obj.goodsName,
            goodsPrice: obj.goodsPrice,
            goodsImage: obj.goodsImage,
            commodityTypeId: obj.commodityTypeId,
            recommend: obj.recommend,
            id: JSON.parse(this.$route.query.obj).id,
          })
          .then((res) => {
            if (res.data.data == 1) {
              alert("修改成功！");
              this.$router.push("/backstage");
            }
          });
      }
    },
  },
  mounted() {
    this.$axios.post("/goods/findSpec").then((res) => {
      let newarr = res.data.data;
      var arr = [];
      for (let i = 0; i < newarr.length; i++) {
        arr[i] = {};
        arr[i].key = newarr[i].specName;
        arr[i].id = newarr[i].id;
        arr[i].value = [];
        arr[i].checkedAttr = [];
        for (let j = 0; j < newarr[i].children.length; j++) {
          var obj = {};
          obj.specId = newarr[i].children[j].specId;
          obj.pspecId = newarr[i].children[j].pspecId;
          obj.value = newarr[i].children[j].specName;

          arr[i].value.push(obj);
        }
        this.SpecsList.push(arr[i]);
      }
      for (let i = 0; i < this.SpecsList.length; i++) {
        var arrss = [];
        arrss = {};
        arrss.values = "";
        this.attribute.push(arrss);
      }
    });

    if (this.$route.query.id != undefined) {
      this.Flog = false;
    }
    if (this.$route.query.obj != undefined) {
      this.fg = false;
      var datas = JSON.parse(this.$route.query.obj);
      this.SkuData[0].goodsName = datas.productName;
      this.SkuData[0].goodsPrice = datas.productMoney;
      this.SkuData[0].goodsImage = datas.productPic;
      this.SkuData[0].commodityTypeId = datas.commodityTypeId;
      this.SkuData[0].recommend = datas.productRecommend;

      // this.$axios
      //   .post("/goods/findDataBySkuId", {
      //     id: datas.skuId,
      //   })
      //   .then((res) => {
      //     this.$axios
      //       .get(`/goods/getAttrList?goodsId=${datas.goodsid}`)
      //       .then((res) => {
      //         for (const key in res.data) {
      //           for (let i = 0; i < this.SpecsList.length; i++) {
      //             if (key == this.SpecsList[i].key) {
      //               var ass = this.$refs.check[i].children[1].children[0]
      //                 .children;
      //               for (let j = 0; j < ass.length; j++) {
      //                 if (ass[j].innerText == res.data[key][0].specName) {
      //                   ass[j].click();
      //                 }
      //               }
      //             }
      //           }
      //         }
      //       });
      //   });
    }
  },
};
</script>
<style scoped>
.sku_select {
  font-size: 14px;
}

.specs_box {
  margin: 10px 0;
}

.specs_item {
  width: 300px;
  height: auto;
  border-radius: 5px;
  border: 1px solid #dcdfe6;
  overflow: hidden;
  display: inline-block;
  margin: 10px;
}

.specs_titt {
  height: 40px;
  line-height: 40px;
  font-size: 14px;
  padding: 0 10px;
  border-bottom: 1px solid #dcdfe6;
}

.specs_key {
  padding: 10px;
}

.specs_add {
  padding: 10px;
}
.btn {
  margin: 20px auto;
  text-align: center;
}
</style>